package com.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.net.URI;

public class PhonePar extends Configured implements Tool {
    // k1           v1
    // 0            13862465004,tom
    // ..           18923423212,jake
    // ..           13832321324,zhansan
    // k2                   v2
    // 13862465004          tom
    //18923423212           jake
    //13832321324           zhansan
    static class PhoneParMapper extends
            Mapper<LongWritable, Text, Text, Text>{
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            String[] datas = value.toString().split(",");
            // datas:["13832321324","zhansan"]
            context.write(new Text(datas[0]),new Text(datas[1]));
        }
    }


    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        // 指定输入输出路径
        Path input = new Path(
                "hdfs://192.168.10.11:9000/phonedata");
        Path output = new Path(
                "hdfs://192.168.10.11:9000/phoneoutput");

        FileSystem fs = FileSystem.get(
                new URI("hdfs://192.168.10.11:9000")
                ,conf);
        if (fs.exists(output)) fs.delete(output,true);
        //构建Job
        Job job = Job.getInstance(conf);
        job.setJobName("phone");
        job.setJarByClass(this.getClass());
        // 指定map类的配置
        job.setMapperClass(PhoneParMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        // 指定reduce类的配置
        job.setNumReduceTasks(3);
        // 设置分区器
        job.setPartitionerClass(PhonePartitioner.class);

        TextInputFormat.addInputPath(job,input);
        TextOutputFormat.setOutputPath(job,output);
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        System.exit(ToolRunner.run(new PhonePar(),args));
    }
}
